/*
 * Copyright (C) 2007-2008  Hylke van der Schaaf
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, in version 3 of the License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package hextd.blackBox;

import hextd.HexTD;
import hextd.core.Context;
import hextd.message.MessageLoadMap;
import hextd.core.MapInfo;

/**
 *
 * @author hylke
 */
public class BBActionMapStart implements BBAction {

	private static final BlackBox.ActionType type = BlackBox.ActionType.MapStart;
	private int gameTime;
	private String map;
	private String mapMd5;
	private String version;

	/** Creates a new instance of BBActionMapStart */
	public BBActionMapStart(int gameTime, String map, String mapMd5, String version) {
		this.gameTime = gameTime;
		this.map = map;
		this.mapMd5 = mapMd5;
		this.version = version;
	}

	public String getMapId() {
		return map;
	}

	@Override
	public BlackBox.ActionType getType() {
		return BBActionMapStart.type;
	}

	@Override
	public int getGameTime() {
		return this.gameTime;
	}

	@Override
	public void execute(Context c) {
		System.out.println("BBActionMapStart::execute: " + c.getGameTime().getTime() + " Loading map " + this.map + ", version " + this.version);
		if (!HexTD.VERSION.equals(this.version)) {
			System.err.println("BBActionMapStart::execute: Warning recoring made with version " + this.version + "\n but this is version " + HexTD.VERSION + ",\n playback may not work as expected!");
			c.showAlert("Warning recoring made with version " + this.version + "\n but this is version " + HexTD.VERSION + ",\n playback may not work as expected!");
		}
		if (!c.getBlackBox().startMap(this.map)) {
			System.err.println("BBActionMapStart::execute: Sync error: Loading map failed!");
			c.showAlert("Loading map failed, playback may not work as expected!");
		}
		MapInfo loadedMap = c.getMapInfo();
		if (!loadedMap.getMapMD5().equalsIgnoreCase(this.mapMd5)) {
			System.err.println("BBActionMapStart::execute: Sync error: Map MD5 does not match: " + loadedMap.getMapMD5() + "=" + this.mapMd5);
			c.showAlert("Loaded map is not the same as map used in replay. Playback may not work as expected!");
		}
		if (c.getGameState() == HexTD.GameState.replaying && c.getActivePlayers() > 1) {
			c.setGameState(HexTD.GameState.mpChecking);
		}
	}

	@Override
	public String getString() {
		return MessageLoadMap.formatMessage(map, mapMd5, version);
	}
}
